<html>
  <head>
    <title>Modifying a global by accident</title>
  </head>

  <body>
    <h1>Modifying a global by accident</h1>

    <script type="text/javascript">
      var i = 1;
      document.writeln("The initial value of i is " + i + ".<br/>");

      /**
       * This function modifies the global variable _i_
       * unintentionally. Errors like this can be difficult
       * to spot--the trick is to look for the _var_ keyword
       * everywhere we know we're not trying to modify
       * global state.
       */
      function modifyGlobalByAccident() {
          for (i = 0; i < 10; i++) {
              document.writeln("In loop: i = " + i + "<br/>");
          }
      }

      modifyGlobalByAccident();

      /**
       * Here we expect the value of _i_ to be one, which
       * is what we initialized it to--but the previous
       * function call modified it by accident.
       */
      document.writeln("The value of i is " + i + " outside the loop!");
    </script>
  </body>
</html>
        